<template>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
        <el-breadcrumb-item>行政审批</el-breadcrumb-item>
        <el-breadcrumb-item>发起申请</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 条件查询 -->
    <el-card class="queryFormElCard mt-4">
        <el-form :model="queryParam" ref="queryFromRef">
            <el-row>
                <el-col :span="5">
                    <el-form-item label="流程标识">
                        <el-input v-model="queryParam.key" placeholder="请输入流程标识" />
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="流程名称">
                        <el-input v-model="queryParam.name" placeholder="请输入流程名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="流程分类">
                        <el-select v-model="queryParam.category" placeholder="请选择流程分类" :clearable="true"
                            :filterable="true">
                            <el-option v-for="(item, index) in categoryList" :label="item.name" :value="item.code"
                                :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-space class="ml-2">
                        <el-button plain type="primary" :icon="Search" @click="querySelective">查询</el-button>
                        <el-button plain :icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-space>
                </el-col>
            </el-row>
        </el-form>
    </el-card>
    <!-- 表格、分页 -->
    <el-card>
        <el-table :data="tableData" border :header-cell-style="{ 'background': '#f2f2f2', 'color': '#515a6e' }"
            style="width: 100%" height="calc(100vh - 310px)" max-height="calc(100vh - 310px)" v-loading="tableLoading">
            <el-table-column prop="processKey" label="流程标识" />
            <el-table-column prop="processName" label="流程名称" />
            <el-table-column prop="category" label="流程分类" />
            <el-table-column prop="version" label="流程版本" />
            <el-table-column label="操作" width="250px">
                <template #default="scope">
                    <el-space>
                        <el-button link type="primary" size="small" :icon="Star"
                            @click="openStartProcessPage(scope.row)">发起</el-button>
                    </el-space>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="currentPageNum" v-model:page-size="currentPageSize"
            :page-sizes="[30, 50, 100, 300, 500]" layout="total, sizes, prev, pager, next, jumper" background
            :total="totalCount" @size-change="changePageSize" @current-change="changePageNum" />
    </el-card>

    <!-- 发起流程 -->
    <el-dialog v-model="formVisible" @close="closeFormDialog" title="发起流程" width="35%">
        <component :is="formComponent" ref="formRef" />
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeFormDialog">取消</el-button>
                <el-button type="primary" @click="submitForm">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { onMounted, ref, reactive, watch, defineAsyncComponent, markRaw, nextTick } from "vue"
import { Refresh, Search, Star } from '@element-plus/icons-vue'
import { querySelectiveReq,startReq } from '@/api/workflow/process/index.js'
import { queryCategoryAllReq } from '@/api/workflow/category/index.js'
import { queryByIdReq } from '@/api/workflow/form/index.js'

import { success } from '@/utils/messageUtils.js';

const categoryList = ref([])
onMounted(() => {
    Promise.all([
        queryCategoryAllReq(),
    ]).then(([categoryAllRes
    ]) => {
        categoryList.value = categoryAllRes.data;
        querySelective();
    });
})

// 条件查询
const queryParam = reactive({
    key: '',
    name: '',
    category: '',
})
const queryFromRef = ref()
const resetQuery = () => {
    queryParam.key = ''
    queryParam.name = ''
    queryParam.category = ''
    queryFromRef.value?.resetFields();
    currentPageNum.value = 1
    querySelective();
}

// 分页查询、条件查询
const tableLoading = ref(false)
const tableData = ref([])
const total = ref()
const querySelective = () => {
    tableLoading.value = true;
    querySelectiveReq(
        currentPageNum.value,
        currentPageSize.value,
        {
            key: queryParam.key ? queryParam.key : '',
            name: queryParam.name ? queryParam.name : '',
            category: queryParam.category ? queryParam.category : '',
        }
    ).then(res => {
        if (res.code == 200) {
            tableData.value = res.data
            total.value = res.total
        }
    }).finally(() => {
        tableLoading.value = false
    })
}
const totalCount = ref(0)
watch(() => total.value, (newValue) => {
    totalCount.value = newValue;
});

const currentPageNum = ref(1)
const currentPageSize = ref(30)
// 翻页
const changePageNum = (pageNum) => {
    currentPageNum.value = pageNum
    querySelective();
}
// 改变页大小
const changePageSize = (pageSize) => {
    currentPageNum.value = 1
    currentPageSize.value = pageSize
    querySelective();
}

// 打开发起流程dialog
const formComponent = ref(null);
const formVisible = ref(false)
const currentProcessDefId = ref()
const openStartProcessPage = async (row) => {
    const res = await queryByIdReq(row.formId);
    if (res.code === 200) {
        const { content: formPath } = res.data;
        // 动态加载组件
        formComponent.value = markRaw(
            defineAsyncComponent(() => import(`/src/views${formPath}`))
        );
        // 等待组件加载并确保 DOM 更新
        currentProcessDefId.value = row.definitionId
        formVisible.value = true
    }
};

const closeFormDialog = () => {
    formVisible.value = false
}

const formRef = ref()
const submitForm = async () => {
    try {
        await formRef.value.validate();
        // 提交
        startReq(currentProcessDefId.value,formRef.value?.formData).then(res=>{
            if(res.code == 200){
                success("发起流程申请成功！");
                closeFormDialog();
            }
        })
    } catch (errors) {
        // 表单校验未通过！
    }
}
</script>

<style>
.queryFormElCard .el-card__body {
    padding-bottom: 0;
}
</style>